<template>
    <div class="carousel-container">
        <!-- 页面头部 -->
        <div class="operation-area flex-between">
            <div class="left">
                <el-button type="primary" @click="handleAdd">
                    <el-icon><Plus /></el-icon>添加轮播图
                </el-button>
            </div>
        </div>

        <!-- 轮播图列表卡片 -->
        <el-card class="table-area" v-loading="loading">
            <!-- 轮播图列表表格 -->
            <el-table v-loading="loading" :data="tableData" border style="width: 100%" :header-cell-style="{
                background: '#f5f7fa',
                color: '#606266',
                fontWeight: 'bold'
            }" row-class-name="table-row" highlight-current-row>
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="title" label="标题" width="150" />
                <el-table-column label="图片" width="200">
                    <template #default="{ row }">
                        <div class="image-preview">
                            <el-image :src="row.imageUrl" :preview-src-list="[row.imageUrl]" :preview-teleported="true"
                                fit="cover" class="preview-image" :initial-index="0" hide-on-click-modal loading="lazy"
                                @error="handleImageError(row)">
                                <template #error>
                                    <div class="image-error">
                                        <el-icon>
                                            <PictureFilled />
                                        </el-icon>
                                        <span>加载失败</span>
                                    </div>
                                </template>
                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" show-overflow-tooltip min-width="200">
                    <template #default="{ row }">
                        <el-tooltip :content="row.description" placement="top" :show-after="500">
                            <span class="description-text">{{ row.description }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="{ row }">
                        <div class="action-buttons">
                            <el-button type="danger" link @click="handleDelete(row)">
                                <el-icon>
                                    <Delete />
                                </el-icon>删除
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="queryFrom.pageNum" v-model:page-size="queryFrom.pageSize"
                    :page-sizes="[5, 10, 15, 20]" :total="queryFrom.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" background />
            </div>
        </el-card>

        <!-- 添加/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加轮播图' : '编辑轮播图'" width="500px"
            :close-on-click-modal="false" :before-close="handleClose" destroy-on-close class="carousel-dialog">
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="formData.title" placeholder="请输入标题" />
                </el-form-item>
                <el-form-item label="图片" prop="imageUrl">
                    <el-upload class="avatar-uploader" action="/api/lideshow/updatefile" :show-file-list="false"
                        :on-success="handleUploadSuccess" :before-upload="beforeUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="formData.description" type="textarea" placeholder="请输入描述" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        {{ submitLoading ? '提交中...' : '确定' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete, PictureFilled } from '@element-plus/icons-vue';
import {
    getCarouselList,
    saveOrUpdateCarousel,
    deleteCarousel,
    updateCarouselStatus
} from '../../api/carousel/index.js';

// 数据定义
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const dialogType = ref('add');
const formRef = ref(null);

// 查询参数
const queryFrom = ref({
    pageNum: 1,
    pageSize: 5,
    total: 0
});

// 表格数据
const tableData = ref([]);

// 获取列表数据
async function fetchList() {
    loading.value = true; // 添加加载状态
    try {
        const params = {
            pageNum: queryFrom.value.pageNum,
            pageSize: queryFrom.value.pageSize
        };

        const res = await getCarouselList(params);
        console.log('轮播图列表响应:', res);

        if (res && res.code === 200) {
            tableData.value = res.data.list || [];
            queryFrom.value.total = res.data.total || 0;
        } else {
            ElMessage.error(res?.msg || '获取数据失败');
        }
    } catch (error) {
        console.error('获取轮播图列表失败:', error);
        ElMessage.error('获取轮播图列表失败');
    } finally {
        loading.value = false;
    }
}

// 修改分页处理函数
const handleSizeChange = (val) => {
    queryFrom.value.pageSize = val;
    queryFrom.value.pageNum = 1; // 切换每页显示数量时重置到第一页
    fetchList();
};

const handleCurrentChange = (val) => {
    queryFrom.value.pageNum = val;
    fetchList();
};

// 表单数据
const formData = ref({
    title: '',
    imageUrl: '',
    linkUrl: '',
    description: '',
    //sortOrder: 0,
    status: 1
});

// 表单验证规则
const rules = {
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' }
    ],
    imageUrl: [
        { required: true, message: '请上传图片', trigger: 'change' }
    ],
    sortOrder: [
        { required: true, message: '请输入排序号', trigger: 'blur' }
    ]
};

// 添加轮播图
const handleAdd = () => {
    dialogType.value = 'add';
    formData.value = {
        title: '',
        imageUrl: '',
        linkUrl: '',
        description: '',
        // sortOrder: 0,
        status: 1
    };
    dialogVisible.value = true;
};

// 编辑轮播图
const handleEdit = (row) => {
    dialogType.value = 'edit';
    formData.value = { ...row };
    imageUrl.value = row.imageUrl;
    dialogVisible.value = true;
};

// 删除轮播图
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该轮播图吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            loading.value = true;
            // 构造完整的 Lideshow 对象
            const lideshowData = {
                id: row.id,
                title: row.title,
                imageUrl: row.imageUrl,
                linkUrl: row.linkUrl,
                description: row.description,
                status: row.status,
                createTime: row.createTime,
                updateTime: row.updateTime
            };

            const res = await deleteCarousel(lideshowData);

            if (res && res.code === 200) {
                ElMessage.success('删除成功');
                // 如果当前页只有一条数据，删除后自动跳转到上一页
                if (tableData.value.length === 1 && queryFrom.value.pageNum > 1) {
                    queryFrom.value.pageNum--;
                }
                await fetchList(); // 刷新列表
            } else {
                ElMessage.error(res?.message || '删除失败');
            }
        } catch (error) {
            console.error('删除失败:', error);
            ElMessage.error(error.message || '删除失败，请稍后重试');
        } finally {
            loading.value = false;
        }
    }).catch(() => {
        // 用户点击取消，不做任何操作
    });
};

// 更新状态
const handleStatusChange = async (row) => {
    try {
        loading.value = true;
        const res = await updateCarouselStatus({
            id: row.id,
            status: row.status
        });
        if (res.code === 200) {
            ElMessage.success('状态更新成功');
        } else {
            row.status = row.status === 1 ? 0 : 1; // 更新失败时恢复状态
            ElMessage.error(res.msg || '状态更新失败');
        }
    } catch (error) {
        row.status = row.status === 1 ? 0 : 1; // 发生错误时恢复状态
        console.error('状态更新失败:', error);
        ElMessage.error('状态更新失败');
    } finally {
        loading.value = false;
    }
};

// 修改 handleSubmit 函数
const handleSubmit = async () => {
    if (!formRef.value) return;

    try {
        // 表单验证
        await formRef.value.validate();
        submitLoading.value = true;

        // 发送请求
        const res = await saveOrUpdateCarousel(formData.value);
        console.log('提交响应:', res);

        // 修改判断条件，直接判断 code
        if (res.code === 200) {
            ElMessage.success({
                message: `${dialogType.value === 'add' ? '添加' : '更新'}成功！`,
                duration: 1500
            });

            // 重置表单数据
            formRef.value.resetFields();
            imageUrl.value = '';
            formData.value = {
                title: '',
                imageUrl: '',
                linkUrl: '',
                description: '',
                status: 1
            };

            // 关闭对话框
            dialogVisible.value = false;

            // 刷新列表数据
            await fetchList();
        } else {
            // 显示错误信息
            ElMessage.error(res.msg || '操作失败');
        }
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error(error.message || '提交失败，请重试');
    } finally {
        submitLoading.value = false;
    }
};

// 图片
const imageUrl = ref('');

// 图片上传相关
const handleUploadSuccess = (response, uploadFile) => {
    if (response.code === 200 && response.data) {
        imageUrl.value = response.data;
        formData.value.imageUrl = response.data;
        ElMessage.success('图片上传成功');
    } else {
        ElMessage.error(response.msg || '图片上传失败');
    }
};

const beforeUpload = (rawFile) => {
    const isJPG = ['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type);
    const isLt2M = rawFile.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!');
        return false;
    }
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
        return false;
    }
    return true;
};

// 处理图片加载失败
const handleImageError = (row) => {
    ElMessage.error('图片加载失败，请检查图片路径或重新上传');
    // 可以在这里设置默认图片路径
    // row.imageUrl = '默认图片路径';
};

// 在 script setup 中添加 handleClose 方法
const handleClose = (done) => {
    ElMessageBox.confirm('确认关闭？未保存的内容将会丢失')
        .then(() => {
            formRef.value?.resetFields();
            imageUrl.value = '';
            done();
        })
        .catch(() => { });
};

onMounted(() => {
    fetchList();
});
</script>

<style lang="scss" scoped>
.carousel-container {
    padding: 20px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 84px);

    .operation-area {
        margin-bottom: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .table-area {
        background-color: #fff;
        box-shadow: 0 1px 4px rgba(0,21,41,.08);
        
        .el-table {
            border-radius: 4px;
            overflow: hidden;
        }

        .image-preview {
            display: flex;
            justify-content: center;
            align-items: center;

            .preview-image {
                width: 120px;
                height: 80px;
                border-radius: 4px;
                box-shadow: 0 2px 4px rgba(0,0,0,.1);
                transition: transform .3s;
                
                &:hover {
                    transform: scale(1.05);
                }
            }

            .image-error {
                width: 120px;
                height: 80px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                background-color: #f5f7fa;
                border-radius: 4px;
                color: #909399;

                .el-icon {
                    font-size: 24px;
                    margin-bottom: 8px;
                }
            }
        }

        .description-text {
            display: inline-block;
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .action-buttons {
            display: flex;
            gap: 12px;
            justify-content: center;

            .el-button {
                padding: 6px 12px;
                display: flex;
                align-items: center;
                gap: 4px;

                .el-icon {
                    font-size: 14px;
                }

                &.el-button--danger {
                    color: #f56c6c;

                    &:hover {
                        color: #ff9999;
                    }
                }
            }
        }
    }

    .pagination-container {
        margin-top: 20px;
        padding: 16px 0;
        display: flex;
        justify-content: flex-end;
    }
}

.carousel-dialog {
    :deep(.el-dialog__body) {
        padding: 24px;
    }

    .avatar-uploader {
        border: 2px dashed var(--el-border-color);
        border-radius: 8px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.3s;

        &:hover {
            border-color: var(--el-color-primary);
            transform: translateY(-2px);
        }

        .avatar {
            width: 200px;
            height: 120px;
            display: block;
            object-fit: cover;
            border-radius: 4px;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 200px;
            height: 120px;
            line-height: 120px;
            text-align: center;
        }
    }
}

// 添加页面进入动画
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.carousel-container {
    animation: fadeInUp 0.3s ease-out;
}
</style>